﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Baidu.Aip.Ocr;
using System.IO;

namespace GetText
{
    public partial class Form1 : Form
    {
        Ocr client;
        string file;
        bool flag;
        List<Rectangle> m_rects;
        public Form1()
        {
            var API_KEY = "自己申请的api key";
            var SECRET_KEY = "自己申请的api key的密码";
            flag = false;
            m_rects = new List<Rectangle>();
            client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超时时间
            InitializeComponent();
        }

        private void Load_Img_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;//该值确定是否可以选择多个文件
            dlg.Title = "请选择文件";
            dlg.Filter = "jpg file(*.jpg)|*.jpg|png file(*.png)|*.png|bmp file(*.bmp)|*.bmp|所有文件(*.*)|*.*";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = dlg.FileName;
                flag = true;
            }
            else
                return;
            Image img = Bitmap.FromFile(file);
            img_show.Image = img;
        }

        private void Get_Text_Click(object sender, EventArgs e)
        {
            if (flag)
            {
                var options = new Dictionary<string, object>{
                    {"language_type", "CHN_ENG"},
                    {"detect_direction", "true"},
                    {"detect_language", "true"},
                    {"probability", "true"}
                };
                var image = File.ReadAllBytes(file);
                m_rects.Clear();
                try
                {
                    var result = client.General(image,options);
                    var jsonFile = "result.json";
                    //found the file exist 
                    if (!File.Exists(jsonFile))
                    {
                        FileStream fs1 = new FileStream(jsonFile, FileMode.Create, FileAccess.ReadWrite);
                        fs1.Close();
                    }
                    //write the json to file 
                    File.WriteAllText(jsonFile, result.ToString());
                    var ob = Convert.ToInt32(result["words_result_num"]);
                    var pl = result["words_result"];
                    var word = "";
                    for (int i = 0; i < ob; i++)
                    {
                        word += Convert.ToString(pl[i]["words"]);
                        var left = Convert.ToInt32(pl[i]["location"]["left"]);
                        var top = Convert.ToInt32(pl[i]["location"]["top"]);
                        var width = Convert.ToInt32(pl[i]["location"]["width"]);
                        var height = Convert.ToInt32(pl[i]["location"]["height"]);
                        m_rects.Add(new Rectangle(left, top, width, height));
                        if (i != ob - 1)
                            word += "\n";
                    }
                    using (FileStream fs = new FileStream("decode.txt", FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                        {
                            sw.WriteLine(word);
                        }
                    }
                    //Rectangle rect = new Rectangle(0, 1, 1, 2);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void GetChinese_Click(object sender, EventArgs e)
        {
            var str = "nihao你好!！";
            Console.WriteLine(getChinese(str));
            int a = 0x4e00, b = 0x9fa5;
            var sd = Convert.ToString(0x4e00, 16);
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.WriteLine(sd);
        }

        string getChinese(string str)
        {
            string result = "";
            int currentcode = -1;
            for (int i = 0; i < str.Length; i++)
            {
                currentcode = (int)str[i];
                if (currentcode > 19968 & currentcode < 0x9FEF)
                {
                    result += str[i].ToString();
                }
            }
            return result;
        }

        private void Encode_Decode_Click(object sender, EventArgs e)
        {
            char[] str = new char[] {
                '#', // #\u0023
                '\u0025', // %
                '\u03a0', // Pi
                '\u03a3',  // Sigma
                '\u4e00',
                '\u9fa5',
                '1','0','0','0'
            };
            Encoding encode = Encoding.UTF8;
            var allCharactersFromEncoding = encode.GetBytes(str);
            ShowArray(allCharactersFromEncoding);
            Console.WriteLine(str);
            Decoder decode = Encoding.UTF8.GetDecoder();
            char[] chs = new char[allCharactersFromEncoding.Length];
            var decodd = decode.GetChars(allCharactersFromEncoding, 0, allCharactersFromEncoding.Length, chs, 0);
            Console.WriteLine(chs);
        }

        public static void ShowArray(Array theArray)
        {
            foreach (Object o in theArray)
            {
                Console.Write("[{0}]", o);
            }
            Console.WriteLine("\n");
        }
        
    }
}
